#!/usr/bin/python3
# _*_ coding: utf-8 _*_
#
# Copyright (C) 2024 - 2024 heihieyouheihei, Inc. All Rights Reserved 
#
# @Time    : 2024/9/20 21:40
# @Author  : Yuyun
# @File    : 中序和后序遍历构造二叉树and给出前序遍历.py
# @IDE     : PyCharm

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def build_tree(self, midorder:list, postorder:list) -> TreeNode:
        if not postorder:
            return None
        #   后序遍历最后值 == 根节点值（左右中）
        root = TreeNode(postorder[-1])
        #   找到跟节点位于 中序列表位置
        root_index = midorder.index(root.val)
        #   根据根节点位置，将中序列表拆分为左子树列表和右子树列表（左中右）
        mid_left = midorder[:root_index]
        mid_right = midorder[root_index + 1:]
        #   将后序列表拆分为左子树列表和右子树列表
        post_left = postorder[:len(mid_left)]
        post_right = postorder[len(mid_left):len(postorder) - 1]
        #   构造根节点左右子树
        root.left = self.build_tree(mid_left, post_left)
        root.right = self.build_tree(mid_right, post_right)
        return root

    def preorder_traversal(self, root:TreeNode, res=None) -> list:
        if not res:
            res = []
        if root:
            res.append(root.val)
            res = self.preorder_traversal(root.left, res)
            res = self.preorder_traversal(root.right, res)
        return res
if __name__ == '__main__':
    while True:
        try:
            #   输入字符串，转化为数组
            # mid, post = input().split()
            # mid_order = list(mid)
            # post_order = list(post)
            #   输入数组
            mid_order = list(map(str, input().split()))
            post_order = list(map(str, input().split()))
            solution = Solution()
            root = solution.build_tree(mid_order, post_order)
            result = solution.preorder_traversal(root)
            print(result)
        except:
            break

